<?php
/**
 * @desc   common php function
 * @author Deng Jie
 * 
 */


/**
 * Returns the equivalent of Apache's $_SERVER['REQUEST_URI'] variable.
 *
 * Because $_SERVER['REQUEST_URI'] is only available on Apache, we generate an
 * equivalent using other environment variables.
 */
function request_uri() {
  if (isset($_SERVER['REQUEST_URI'])) {
    $uri = $_SERVER['REQUEST_URI'];
  }
  else {
    if (isset($_SERVER['argv'])) {
      $uri = $_SERVER['SCRIPT_NAME'] . '?' . $_SERVER['argv'][0];
    }
    elseif (isset($_SERVER['QUERY_STRING'])) {
      $uri = $_SERVER['SCRIPT_NAME'] . '?' . $_SERVER['QUERY_STRING'];
    }
    else {
      $uri = $_SERVER['SCRIPT_NAME'];
    }
  }
  // Prevent multiple slashes to avoid cross site requests via the Form API.
  $uri = '/' . ltrim($uri, '/');

  return $uri;
}

/**
 * Returns the requested URL path of the page being viewed.
 *
 * Examples:
 * - http://example.com/node/306 returns "node/306".
 * - http://example.com/drupalfolder/node/306 returns "node/306" while
 *   base_path() returns "/drupalfolder/".
 * - http://example.com/path/alias (which is a path alias for node/306) returns
 *   "path/alias" as opposed to the internal path.
 * - http://example.com/index.php returns an empty string (meaning: front page).
 * - http://example.com/index.php?page=1 returns an empty string.
 *
 * @return
 *   The requested Drupal URL path.
 *
 * @see current_path()
 */
function request_path() {
	static $path;

	if (isset($path)) {
		return $path;
	}

	if (isset($_GET['q'])) {
		// This is a request with a ?q=foo/bar query string. $_GET['q'] is
		// overwritten in drupal_path_initialize(), but request_path() is called
		// very early in the bootstrap process, so the original value is saved in
		// $path and returned in later calls.
		$path = $_GET['q'];
	}
	elseif (isset($_SERVER['REQUEST_URI'])) {
		// This request is either a clean URL, or 'index.php', or nonsense.
		// Extract the path from REQUEST_URI.
		$request_path = strtok($_SERVER['REQUEST_URI'], '?');
		$base_path_len = strlen(rtrim(dirname($_SERVER['SCRIPT_NAME']), '\/'));
		// Unescape and strip $base_path prefix, leaving q without a leading slash.
		$path = substr(urldecode($request_path), $base_path_len + 1);
		// If the path equals the script filename, either because 'index.php' was
		// explicitly provided in the URL, or because the server added it to
		// $_SERVER['REQUEST_URI'] even when it wasn't provided in the URL (some
		// versions of Microsoft IIS do this), the front page should be served.
		if ($path == basename($_SERVER['PHP_SELF'])) {
			$path = '';
		}
	}
	else {
		// This is the front page.
		$path = '';
	}

	// Under certain conditions Apache's RewriteRule directive prepends the value
	// assigned to $_GET['q'] with a slash. Moreover we can always have a trailing
	// slash in place, hence we need to normalize $_GET['q'].
	$path = trim($path, '/');

	return $path;
}